import { getSession, setSession } from '@/utils/storage'
import { create } from 'zustand'
import { subscribeWithSelector } from 'zustand/middleware'

interface State {
  token: string
  setToken: (token: string, reload?: boolean) => void
}

const LocalKey = 'token'

const useTokenStore = create<State>()(
  subscribeWithSelector(set => ({
    token: getSession<string>(LocalKey) || '',
    setToken: (token, reload = false) => {
      setSession(LocalKey, token)
      if (!reload) {
        set({ token })
      }
    }
  }))
)

export function getToken() {
  return useTokenStore.getState().token
}

export function clearToken() {
  useTokenStore.getState().setToken('')
}

export default useTokenStore
